package com.hanxiaozhang.importexcelnew;

import com.hanxiaozhang.dictonecode.dao.DictOneDao;
import com.hanxiaozhang.dictonecode.domain.DictOneDO;
import com.hanxiaozhang.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 〈一句话功能简述〉<br>
 * 〈数据字典数据导入〉
 *
 * @author hanxinghua
 * @create 2021/12/12
 * @since 1.0.0
 */
@Slf4j
@Service
public class DictSaveExcelNewServiceImpl implements SaveExcelNewService<DictOneDO> {


    @Resource
    private DictOneDao dictOneDao;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ErrorInfoEntity batchSave(List<DictOneDO> list, CyclicBarrier barrier, AtomicBoolean rollbackFlag) throws Exception {
        log.info("save(),[{}]", Thread.currentThread().getName());
        // 其他线程异常手工回滚
        if (rollbackFlag.get()) {
            String message = "子线程未全部执行成功，对线程[" + Thread.currentThread().getName() + "]进行回滚";
            throw new Exception(message);
        }
        try {
            //创建返回错误信息实体
            ErrorInfoEntity errorInfoEntity = new ErrorInfoEntity();
            //业务操作
            List<DictOneDO> errorList = handleDict(list);
            //赋值错误数据
            errorInfoEntity.setErrorList(errorList);
            barrier.await();
            if (rollbackFlag.get()) {
                String message = "子线程未全部执行成功，对线程[" + Thread.currentThread().getName() + "]进行回滚";
                throw new Exception(message);
            }
            return errorInfoEntity;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
            rollbackFlag.set(true);
            barrier.await();
            throw e;
        }
    }


    /**
     * 处理相关数据
     *
     * @param list
     * @return
     */
    private List<DictOneDO> handleDict(List<DictOneDO> list) {
        List<DictOneDO> errorList = new ArrayList<>();
        list.forEach(x -> {
            boolean flag = true;
            List<String> errorMsg = new ArrayList<>();
            //模拟一个业务数据错误，姓名不能为空
            if (StringUtil.isBlank(x.getName())) {
                errorMsg.add("姓名不能为空!");
                flag = false;
                throw new RuntimeException();
            }
            //模拟一个业务数据错误，类型不能为空
            if (StringUtil.isBlank(x.getType())) {
                errorMsg.add("类型不能为空!");
                flag = false;
            }
            if (flag) {
                dictOneDao.save(x);
            } else {
                x.setRemarks(String.join("\n", errorMsg));
                errorList.add(x);
            }
        });

        return errorList;
    }


}
